#ifndef _MESSAGE_FACTORY_H_
#define _MESSAGE_FACTORY_H_

#include <unordered_map>
#include "common_define.h"
#include "common_singleton.h"
#include "jsonmessage.h"
#include "retcodes.h"

class IPBMsgCreatorInterface
{
public:
	virtual ~IPBMsgCreatorInterface( ) { }
	virtual CJsonMessageBase* GetMsg( ) = 0;
};

template< typename T >
class CPBMsgCreator : public IPBMsgCreatorInterface
{
public:
	CPBMsgCreator( ) {  }
	virtual CJsonMessageBase* GetMsg( )
	{
		return &t_;
	}
	
public:
	T t_;
};

class CPBMsgFactory
{
public:
	CPBMsgFactory( ) { }
	~CPBMsgFactory( )
	{
		for( TMsgCreatorMap::iterator iter = msg_map_.begin( ); iter != msg_map_.end( ); ++iter )
		{
			IPBMsgCreatorInterface* itf = iter->second;	
			if( NULL != itf )
			{
				delete itf;
			}
		}
		msg_map_.clear( );
	}


	CJsonMessageBase* CreateMsg( uint32_t msg_id )
	{
		TMsgCreatorMap::iterator it = msg_map_.find( msg_id );
		if ( it == msg_map_.end( ) )
		{
			return NULL;
		}

		IPBMsgCreatorInterface* _interface = it->second;
		if (_interface == NULL )
		{
			return NULL;
		}

		return _interface->GetMsg( );
	}

	template< typename T >int RegistePBMsg( uint32_t msg_id )
	{
		CPBMsgCreator< T >* msg_creator = new CPBMsgCreator< T >( );

		msg_map_[ msg_id ] = msg_creator;

		return ::common::SUCCEED;
	}

public:
	typedef std::unordered_map<uint32_t, IPBMsgCreatorInterface*> TMsgCreatorMap;
	TMsgCreatorMap msg_map_;
};

#endif


